from docx import Document
from docx.shared import Inches, Cm
from io import BytesIO
from concurrent.futures import ThreadPoolExecutor
import requests


def insert_images_parallel(doc_path, image_urls, max_workers=4):
    """并行下载并插入图片到Word文档"""
    doc = Document()

    # 定义图片处理函数
    def process_image(url):
        response = requests.get(url)
        if response.status_code == 200:
            return BytesIO(response.content)
        return None

    # 使用线程池并行下载
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        image_streams = list(executor.map(process_image, image_urls))

    # 插入图片到文档（顺序保证）
    for stream in filter(None, image_streams):
        paragraph = doc.add_paragraph()
        run = paragraph.add_run()
        run.add_picture(stream, width=Cm(10))  # 统一宽度为10厘米
        stream.close()  # 显式关闭流

    doc.save(doc_path)


# 使用示例
image_urls = [
    'm:/',
    'https://example.com/image2.png',
    'https://example.com/image3.webp'
]
insert_images_parallel("output.docx", image_urls)